package com.webflux.springwebflux.service.imp;

import com.webflux.springwebflux.dao.TestDao;
import com.webflux.springwebflux.pojo.Test;
import com.webflux.springwebflux.service.TestService;
import org.jooq.DSLContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.r2dbc.core.R2dbcEntityTemplate;
import org.springframework.data.relational.core.query.Criteria;
import org.springframework.data.relational.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.transaction.reactive.TransactionalOperator;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.List;

@Service
public class TestServiceImpl implements TestService {
    @Autowired
    private TestDao testDao;
    @Autowired
    private R2dbcEntityTemplate r2dbcEntityTemplate;

    @Autowired
    private TransactionalOperator operator;

    @Override
    public Mono<Test> test() {
        //return testDao.getTestInfoById(1);
        //return r2dbcEntityTemplate.selectOne(Query.query(Criteria.where("id").is(1)), Test.class);

        return Mono.deferContextual(contextView -> {
            String id = contextView.get("id");
            String name = contextView.get("name");
            System.out.println("id:" + id + " name:" + name);
            return r2dbcEntityTemplate.selectOne(Query.query(Criteria.where("id").is(1)), Test.class);
        });

    }

    @Override
    public Flux<Test> list() {
        //return  testDao.getList();
        return r2dbcEntityTemplate.select(Query.query(Criteria.empty()), Test.class);
    }

    @Override
    public Mono<Page<Test>> page() {
        Pageable pageable = PageRequest.of(0, 10, Sort.by(Sort.Direction.DESC, "id"));

        // 构建查询条件（可选）
        Query query = Query.query(Criteria.where("id").is(1));

        // 添加分页参数
        query = query.limit(pageable.getPageSize())
                .offset((long) pageable.getPageNumber() * pageable.getPageSize())
                .sort(pageable.getSort());

        // 查询当前页的数据
        Mono<List<Test>> tests = r2dbcEntityTemplate
                .select(Test.class)
                .matching(query)
                .all()
                .collectList();

        // 查询总记录数
        Mono<Long> total = r2dbcEntityTemplate
                .select(Test.class)
                .matching(query)
                .count();

        // 组合结果，返回 Page<User>
        return Mono.zip(tests, total)
                .map(tuple -> new PageImpl<Test>(tuple.getT1(), pageable, tuple.getT2()));
    }


    private Mono<Test> update(Test test) {

        return operator.transactional(Mono.defer(() -> r2dbcEntityTemplate.update(test))
                .then(Mono.defer(() -> r2dbcEntityTemplate.delete(test))));

    }

}
